package com.hmall.search.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.QuestParams;
import com.hmall.search.pojo.SearchItem;
import com.hmall.search.service.SearchService;
import org.apache.lucene.analysis.hi.HindiStemFilterFactory;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImp implements SearchService {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public List<String> getSuggestion(String completion) {
        SearchRequest request = new SearchRequest("item");
        request.source().fetchSource(new String[0], null);
        request.source().suggest(new SuggestBuilder().
                addSuggestion("my_suggestion", SuggestBuilders
                        .completionSuggestion("suggestion")
                        .size(10).skipDuplicates(true).prefix(completion)
                )
        );
        SearchResponse responses = null;
        try {
            responses = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        CompletionSuggestion suggestion = responses.getSuggest().getSuggestion("my_suggestion");
        List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
        List<String> list = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            list.add(option.getText().string());

        }
        return list;
    }

    @Override
    public Map<String, List<String>> getFilters(QuestParams params) throws IOException {
        SearchRequest request = new SearchRequest("item");
        request.source().size(0);
        buildBasicQuery(request, params);
        request.source().aggregation(
                AggregationBuilders.terms("brandAgg")
                        .field("brand").size(20)
        );
        request.source().aggregation(
                AggregationBuilders.terms("categoryAgg")
                        .field("category").size(20)
        );
        SearchResponse response =restHighLevelClient.search(request,RequestOptions.DEFAULT);
        Map<String,List<String>> map = new HashMap<>(2);
        Aggregations aggregations =response.getAggregations();
        Terms brandAgg=aggregations.get("brandAgg");
        List<String>list=new ArrayList<>();
        for (Terms.Bucket bucket:brandAgg.getBuckets()){
            String key =bucket.getKeyAsString();
            list.add(key);
        }
        map.put("brand",list);
        Terms categoryAgg=aggregations.get("categoryAgg");
        List<String>stringList=new ArrayList<>();
        for (Terms.Bucket bucket:categoryAgg.getBuckets()){
            String key =bucket.getKeyAsString();
            list.add(key);
        }
        map.put("category",stringList);
        return map;
    }

    @Override
    public PageDTO<SearchItem> searchList(QuestParams params) {
        try {
            SearchRequest request = new SearchRequest("item");
            buildBasicQuery(request, params);
            int page=params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            String sortBy = params.getSortBy();
            if ("sold".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.DESC);
            } else if ("price".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.ASC);
            }
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            SearchResponse response =restHighLevelClient.search(request,RequestOptions.DEFAULT);
            SearchHits searchHits=response.getHits();
            long total = searchHits.getTotalHits().value;
            SearchHit[] hits = searchHits.getHits();
            List<SearchItem> list=new ArrayList<>();
            for (SearchHit his :hits){
                String json =his.getSourceAsString();
                SearchItem searchItem = MAPPER.readValue(json, SearchItem.class);
                Map<String, HighlightField> map = his.getHighlightFields();
                if (map != null && map.size() > 0) {
                    HighlightField field = map.get("name");
                    String value = field.getFragments()[0].string();
                    searchItem.setName(value);
                }
                list.add(searchItem);
            }
            return new PageDTO<>(total,list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    private void buildBasicQuery(SearchRequest request, QuestParams params) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        Long minPrice = params.getMinPrice();
        Long maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100).lte(maxPrice * 100));
        }
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        );

        request.source().query(queryBuilder);
    }
}

